package com.rabbiter.oes.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.oes.entity.JudgeQuestion;
import com.rabbiter.oes.entity.MultiQuestion;
import com.rabbiter.oes.entity.PaperManage;
import com.rabbiter.oes.mapper.JudgeQuestionMapper;
import com.rabbiter.oes.mapper.PaperMapper;
import com.rabbiter.oes.service.JudgeQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeQuestionServiceImpl extends ServiceImpl<JudgeQuestionMapper, JudgeQuestion> implements JudgeQuestionService {

    // 试卷与题目对应关系
    @Autowired
    private PaperMapper paperMapper;

    @Override
    public List<JudgeQuestion> findByIdAndType(Integer paperId) {
        LambdaQueryWrapper<PaperManage> paperWrapper = Wrappers.lambdaQuery(PaperManage.class).eq(PaperManage::getQuestionType, 3).eq(PaperManage::getPaperId, paperId);
        List<PaperManage> paperManages = paperMapper.selectList(paperWrapper);
        if (CollectionUtil.isNotEmpty(paperManages)) {
            // 筛出题目id
            List<Integer> questionIds = paperManages.stream().map(PaperManage::getQuestionId).collect(Collectors.toList());
            // 查出题目信息
            return baseMapper.selectBatchIds(questionIds);
        }
        return new ArrayList<JudgeQuestion>();
    }

    @Override
    public IPage<JudgeQuestion> findAll(Page<JudgeQuestion> page) {
        return baseMapper.selectPage(page, Wrappers.lambdaQuery());
    }

    @Override
    public JudgeQuestion findOnlyQuestionId() {
        LambdaQueryWrapper<JudgeQuestion> wrapper = Wrappers.lambdaQuery(JudgeQuestion.class);
        wrapper.orderByDesc(JudgeQuestion::getQuestionId);
        List<JudgeQuestion> judgeQuestions = baseMapper.selectList(wrapper);
        if (CollectionUtil.isNotEmpty(judgeQuestions)) {
            return judgeQuestions.get(0);
        }else {
            JudgeQuestion judgeQuestion = new JudgeQuestion();
            judgeQuestion.setQuestionId(1);
            return judgeQuestion;
        }
    }

    @Override
    public Integer add(JudgeQuestion judgeQuestion) {
        baseMapper.insert(judgeQuestion);
        return judgeQuestion.getQuestionId();
    }

    @Override
    public List<Integer> findBySubject(Integer pageNo) {
        return baseMapper.findBySubject(pageNo);
    }

    @Override
    public int edit(JudgeQuestion judgeQuestion) {
        return baseMapper.updateById(judgeQuestion);
    }
}
